#include "Timer.h"

#include "ClockSystem.h"

Timer::Timer(ClockSystem* ref)
{
	clock = ref;

	Reset();
	Start();
}

void Timer::Start()
{
	isRunning = true;
}

void Timer::Pause()
{
	isRunning = false;
}

void Timer::Reset()
{
	for(int i = 0; i < TIMER_AVERAGE_FACTOR; ++i)
	{
		prevDelta[i] = 0.0f;
	}

	speed = 1.0f;
	currentAverageDelta = 0.0f;
	currentDelta = 0.0f;
	totalTime = 0.0;
}
	
void Timer::Update()
{
	if(!isRunning)
		return;

	currentDelta = clock->GetDeltaTimeF();

	if(currentDelta > 0.5f)
		currentDelta = 0.5f;

	currentDelta *= speed;

	currentAverageDelta = currentDelta;

	for(int i = 0; i < TIMER_AVERAGE_FACTOR; ++i)
	{
		currentAverageDelta += prevDelta[i];
	}

	currentAverageDelta /= (TIMER_AVERAGE_FACTOR + 1);

	for(int i = TIMER_AVERAGE_FACTOR - 1; i > 0; --i)
	{
		prevDelta[i] = prevDelta[i - 1];
	}

	prevDelta[0] = currentDelta;

	totalTime += currentDelta;
}